package com.ruoyi.asset.service.impl;

import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.asset.utils.QrUtil;
import com.ruoyi.base.domain.BaseCategory;
import com.ruoyi.base.domain.BaseModel;
import com.ruoyi.base.domain.BaseOrganization;
import com.ruoyi.base.domain.BaseWarehouse;
import com.ruoyi.base.service.IBaseCategoryService;
import com.ruoyi.base.service.IBaseModelService;
import com.ruoyi.base.service.IBaseOrganizationService;
import com.ruoyi.base.service.IBaseWarehouseService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.AssetInfoMapper;
import com.ruoyi.asset.domain.AssetInfo;
import com.ruoyi.asset.service.IAssetInfoService;

import javax.annotation.PostConstruct;
import javax.validation.Validator;

/**
 * 资产信息Service业务层处理
 * 
 * @author yepanpan
 * @date 2024-12-20
 */
@Service
@Slf4j
public class AssetInfoServiceImpl implements IAssetInfoService 
{

    public static final String CACHE_MAP = "asset_info";
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AssetInfoMapper assetInfoMapper;

    @Autowired
    private IBaseCategoryService baseCategoryService;

    @Autowired
    private IBaseWarehouseService baseWarehouseService;

    @Autowired
    private IBaseOrganizationService baseOrganizationService;

    @Autowired
    private IBaseModelService baseModelService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;



    @PostConstruct
    public int reCache(){
        redisCache.deleteObject(CACHE_MAP);
        return 0;
    }

    /**
     * 查询资产信息
     *
     * @param num 资产编码
     * @return 资产信息
     */
    @Override
    public String selectMaxAssetInfoNum(String num){
        return assetInfoMapper.selectMaxAssetInfoNum(num);
    }


    /**
     * 查询资产信息
     *
     * @param num 资产编码
     * @return 资产信息
     */
    @Override
    public AssetInfo selectAssetInfoByNum(String num){
        String key = "num_"+num;
        Long id = redisCache.getCacheMapValue(CACHE_MAP, key);
        if(id != null){
            return selectAssetInfoById(id);
        }
        AssetInfo assetInfo = assetInfoMapper.selectAssetInfoByNum(num);
        if(assetInfo != null){
            fillRelInfo(Collections.singletonList(assetInfo));
            redisCache.setCacheMapValue(CACHE_MAP, key, assetInfo.getId());
            redisCache.setCacheMapValue(CACHE_MAP, "id_"+ assetInfo.getId(), assetInfo);
        }
        return assetInfo;
    }

    /**
     * 查询资产信息
     * 
     * @param id 资产信息主键
     * @return 资产信息
     */
    @Override
    public AssetInfo selectAssetInfoById(Long id)
    {
        String key = "id_"+id;
        AssetInfo assetInfo = redisCache.getCacheMapValue(CACHE_MAP, key);
        if(assetInfo != null){
            return assetInfo;
        }

        assetInfo = assetInfoMapper.selectAssetInfoById(id);
        if(assetInfo != null){
            fillRelInfo(Collections.singletonList(assetInfo));
            redisCache.setCacheMapValue(CACHE_MAP, key, assetInfo);
            redisCache.setCacheMapValue(CACHE_MAP, "num_"+ assetInfo.getNum(), assetInfo.getId());
        }
        return assetInfo;
    }

    public void fillRelInfo(List<AssetInfo> list){
        for (AssetInfo row:list){
            if(row.getCateId() != null){
                BaseCategory baseCategory = baseCategoryService.selectBaseCategoryById(row.getCateId());
                if(baseCategory != null){
                    row.setCateName(baseCategory.getName());
                }
            }

            if(row.getOrgId() != null){
                BaseOrganization baseOrganization = baseOrganizationService.selectBaseOrganizationById(row.getOrgId());
                if(baseOrganization != null){
                    row.setOrgName(baseOrganization.getName());
                }
            }

            if(row.getModelId() != null){
                BaseModel baseModel = baseModelService.selectBaseModelById(row.getModelId());
                if(baseModel != null){
                    row.setModelName(baseModel.getName());
                }
            }

            if(row.getDeptId() != null){
                SysDept sysDept = deptService.selectDeptById(row.getDeptId());
                if(sysDept != null){
                    row.setDeptName(sysDept.getDeptName());
                }
            }

            if(row.getUserId() != null){
                SysUser sysUser = userService.selectUserById(row.getUserId());
                if(sysUser != null){
                    row.setUserName(sysUser.getUserName());
                }
            }


            if(row.getHouseId() != null){
                BaseWarehouse baseWarehouse = baseWarehouseService.selectBaseWarehouseById(row.getHouseId());
                if(baseWarehouse != null){
                    row.setHouseName(baseWarehouse.getName());
                }
            }
        }
    }

    /**
     * 查询资产信息列表
     * 
     * @param assetInfo 资产信息
     * @return 资产信息
     */
    @Override
    public List<AssetInfo> selectAssetInfoList(AssetInfo assetInfo)
    {
        List<AssetInfo> list = assetInfoMapper.selectAssetInfoList(assetInfo);
        if(StringUtils.isNotEmpty(list)){
            fillRelInfo(list);
        }
        return list;
    }

    /**
     * 新增资产信息
     * 
     * @param assetInfo 资产信息
     * @return 结果
     */
    @Override
    public int insertAssetInfo(AssetInfo assetInfo)
    {
        assetInfo.setCreateTime(DateUtils.getNowDate());
        validate(assetInfo);
        return assetInfoMapper.insertAssetInfo(assetInfo);
    }

    /**
     * 修改资产信息
     * 
     * @param assetInfo 资产信息
     * @return 结果
     */
    @Override
    public int updateAssetInfo(AssetInfo assetInfo)
    {
        assetInfo.setUpdateTime(DateUtils.getNowDate());
        validate(assetInfo);
        return assetInfoMapper.updateAssetInfo(assetInfo) + reCache();
    }

    /**
     * 验证数据
     * @param assetInfo
     */
    public void validate(AssetInfo assetInfo){
        BeanValidators.validateWithException(validator, assetInfo);
        if(assetInfo.getIsUse().equalsIgnoreCase("Y") && assetInfo.getUserId() == null){
            throw new ServiceException("在用的资产必须有使用人");
        }

        if(assetInfo.getIsUse().equalsIgnoreCase("N") && assetInfo.getUserId() != null){
            throw new ServiceException("闲置资产不能有使用人");
        }
    }

    /**
     * 批量删除资产信息
     * 
     * @param ids 需要删除的资产信息主键
     * @return 结果
     */
    @Override
    public int deleteAssetInfoByIds(Long[] ids)
    {
        return assetInfoMapper.deleteAssetInfoByIds(ids) + reCache();
    }

    /**
     * 删除资产信息信息
     * 
     * @param id 资产信息主键
     * @return 结果
     */
    @Override
    public int deleteAssetInfoById(Long id)
    {
        return assetInfoMapper.deleteAssetInfoById(id) + reCache();
    }

    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importData(List<AssetInfo> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, Long> relCache = new HashMap<>();
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        deptList.forEach(d->{
            relCache.put("dept_"+d.getDeptName(), d.getDeptId());
        });
        List<SysUser> userList = userService.selectUserList(new SysUser());
        userList.forEach(u->{
            relCache.put("user_"+u.getNickName(), u.getUserId());
        });
        for (AssetInfo row : dataList)
        {
            try
            {
                if(StringUtils.isEmpty(row.getCateName())){
                    throw new ServiceException(row.getNum() + " 的分类不能为空");
                }
                String key = "cate_"+row.getCateName();
                Long cateId = relCache.get(key);
                if(cateId == null){
                    BaseCategory baseCategory = baseCategoryService.selectBaseCategoryByName(row.getCateName());
                    if(baseCategory == null) {
                        throw new ServiceException(row.getNum() + " 分类不存在");
                    }
                    cateId = baseCategory.getId();
                    relCache.put(key, cateId);
                }
                row.setCateId(cateId);

                if(StringUtils.isNotEmpty(row.getOrgName())){
                    key = "org_"+row.getOrgName();
                    Long orgId = relCache.get(key);
                    if(orgId == null) {
                        BaseOrganization baseOrganization = baseOrganizationService.selectBaseOrganizationByName(row.getOrgName());
                        if (baseOrganization == null) {
                            throw new ServiceException(row.getOrgName() + " 厂商不存在");
                        }
                        orgId = baseOrganization.getId();
                        relCache.put(key, orgId);
                    }
                    row.setOrgId(orgId);
                }

                if(StringUtils.isNotEmpty(row.getModelName())){
                    key = "model_"+row.getModelName();
                    Long modelId = relCache.get(key);
                    if(modelId == null){
                        BaseModel baseModel = baseModelService.selectBaseModelById(cateId, row.getModelName());
                        if(baseModel == null){
                            throw new ServiceException(row.getCateName() + " " + row.getOrgName() + " 型号不存在");
                        }
                        modelId = baseModel.getId();
                        relCache.put(key, modelId);
                    }
                    row.setModelId(modelId);
                }

                if(StringUtils.isNotEmpty(row.getDeptName())){
                    key = "dept_"+row.getDeptName();
                    Long deptId = relCache.get(key);
                    if(deptId == null){
                        throw new ServiceException(row.getDeptName() + " 部门不存在");
                    }
                    row.setDeptId(deptId);
                }

                if(StringUtils.isNotEmpty(row.getUserName())){
                    key = "user_"+row.getUserName();
                    Long userId = relCache.get(key);
                    if(userId == null){
                        throw new ServiceException(row.getUserName() + " 用户不存在");
                    }
                    row.setUserId(userId);
                }

                // 验证是否存在这个数据
                AssetInfo old = assetInfoMapper.selectAssetInfoByNum(row.getNum());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertAssetInfo(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、资产 " + row.getNum() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateAssetInfo(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、资产 " + row.getNum() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、资产 " + row.getNum() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、资产 " + row.getNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 批量生成二维码
     *
     * @return 结果
     */
    @Override
    public int batchQr(){
        String configSize = configService.selectConfigByKey("qr.size");
        Integer qrSize = StringUtils.isEmpty(configSize) ? 300 : Integer.parseInt(configSize);

        //创建或清空目录
        String path = RuoYiConfig.getProfile()+"/qr/";
        File qrFolder = new File(path);
        if(!qrFolder.exists()){
            qrFolder.mkdirs();
        }else{
            for(File qf:qrFolder.listFiles()){
                if(qf.isFile()){
                    qf.delete();
                }
            }
        }

        AssetInfo aic = new AssetInfo();
        aic.setStatus("-9");
        List<AssetInfo> list = assetInfoMapper.selectAssetInfoList(aic);
        new Thread(()->{
            //遍历资产并生成
            list.forEach(e->{
                String qrPath = path + e.getId()+".png";
                QrUtil.genQr("asset://"+e.getNum(), qrPath, qrSize);
            });
        }).start();

        return list.size();
    }

}
